/**
 * @description 本地数据操作
 */

import { treer, objecter, loger, SqliteDataBase, sqliter } from '@daelui/dogjs/dist/components'
import uniFiler from '@/components/libs/uni-filer.js'
import { queryTables, queryTableData, uploadImage } from '@/api/system/app.js'

// 初始化本地数据库
// #ifdef APP-PLUS
export const database = new SqliteDataBase({
  dbName: 'app_maintain',
  dbTables: []
})
// #endif

export default {
  // 初始化本地数据
  initLocalData () {
    // 初始化本地数据表
    initBaseSql().finally(() => {
      // 查询所有的配置表
      queryTables().then(res => {
        let data = res.data
        data = Array.isArray(data) ? data : []
        let defers = []
        data.forEach(item => {
          defers.push(
            queryTableData({
              url: item.url
            }).then(res => {
              let data = res.data
              data = Array.isArray(data) ? data : []
              item.data = data
            })
          )
        })
        // 更新配置表数据
        let defer = Promise.resolve(true)
        Promise.allSettled(defers).then(() => {
          data.forEach(item => {
            defer = defer.then(() => {
              // 先删除旧数据
              return database.deleteAll(item.tableName).then(() => {
                // 添加数据
                return database.insertAll(item.tableName, item.data || [])
              })
            })
          })
        })
      })
    })
  },

  // 初始化数据表
  initBaseSql (callback) {
    return new Promise((resolve, reject) => {
      uniFiler.readFile('_www/static/sql/app_maintain_sqlite_init.sql').then(e => {
        let sql = e.target.result
        let sqls = sql.split(';')
        database.executeSql(sqls).then(e => {
          console.log('initBaseSql success')
          resolve()
        }).catch(e => {
          console.log('initBaseSql error')
          reject(e)
        })
        // let dbName = 'app_maintain'
        // sqliter.openDB(dbName).then(() => {
        //   plus.sqlite.executeSql({
        //     name: dbName,
        //     sql: sqls,
        //     success(res) {
        //       console.log(789123)
        //       resolve(res)
        //     },
        //     fail(e) {
        //       console.log(e)
        //       reject(e)
        //     }
        //   })
        // })
      }).catch(e => {
        console.log('initBaseSql error')
        console.log(e)
        reject(e)
      })
    })
  },

  // 查询养护路段列表
  queryMaintainSectionsList () {
    return database.table('mp_sections').select().then(list => {
      list = Array.isArray(list) ? list : []
      list.forEach(item => {
        item.value = item.sectionId
        item.text = item.sectionName
      })
      return list
    })
  },

  // 查询病害类型列表
  async queryDiseaseTypeList () {
    let types = await database.table('mp_asset_type').select()
    types = Array.isArray(types) ? types : []
    types.forEach(item => {
      item.value = item.id
      item.text = item.title
    })
    let assets = await database.table('mp_assets').select()
    assets = Array.isArray(assets) ? assets : []
    assets.forEach(item => {
      item.value = item.assetId
      item.text = item.assetName
    })
    let diseaseTypes = await database.table('mp_disease_type').select()
    diseaseTypes = Array.isArray(diseaseTypes) ? diseaseTypes : []
    diseaseTypes.forEach(item => {
      item.value = item.diseaseTypeId
      item.text = item.diseaseName
    })
    types.forEach(item => {
      item.children = assets.filter(node => String(node.typeId) === String(item.id))
      item.children.forEach(node => {
        node.value = item.id + '-' + node.assetId
        node.children = diseaseTypes.filter(sec => String(sec.assetId) === String(node.assetId))
        node.children.forEach(sec => {
          sec.value = item.id + '-' + node.assetId + '-' + sec.diseaseTypeId
        })
      })
    })

    return types
  },

  // 查询字典列表
  async queryDictMap () {
    return database.table('mp_dict_data').select().then(list => {
      list = Array.isArray(list) ? list : []
      let map = { type: {} }
      list.forEach(item => {
        if (!map.type[item.dictType]) {
          map.type[item.dictType] = []
        }
        item.value = item.dictValue
        item.text = item.dictLabel
        map.type[item.dictType].push(item)
      })
      return map
    })
  },

  // 查询养护方法列表
  queryContractSectionItemsList () {
    return database.table('mp_contract_section_items').select().then(list => {
      list = Array.isArray(list) ? list : []
      list.forEach(item => {
        item.value = item.itemId
        item.text = item.itemName
      })
      return list
    })
  },

}
